package controllers

import (
	beego "github.com/beego/beego/v2/server/web"
	"github.com/jinzhu/gorm"
	"orange/models"
)

type AdvuetController struct {
	beego.Controller
}
type Rer struct {
	Code string
	Msg  string
	Data interface{}
}

func (c *AdvuetController) Add() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	name := c.GetString("name")
	address := c.GetString("address")
	stu := models.Advert{
		Name:    name,
		Address: address,
	}
	err := models.DB.Debug().Create(&stu).Error
	if err != nil {
		c.Data["json"] = Rer{"500", "添加失败", nil}
		c.ServeJSON(true)
	} else {
		c.Data["json"] = Rer{"200", "添加成功", nil}
		c.ServeJSON(true)
	}
}
func (c *AdvuetController) List() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	page, _ := c.GetInt("page", 1)
	size, _ := c.GetInt("size", 5)
	offset := (page - 1) * size
	var addgood []models.Advert
	models.DB.Debug().Offset(offset).Limit(size).Find(&addgood)
	c.Data["json"] = Rer{"200", "查询成功", addgood}
	c.ServeJSON(true)

}
func (c *AdvuetController) Del() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	err := models.DB.Debug().Delete(&models.Advert{}, id)
	if err != nil {
		c.Data["json"] = Rer{"500", "删除失败", nil}
		c.ServeJSON(true)
	} else {
		c.Data["json"] = Rer{"200", "删除成功", nil}
		c.ServeJSON(true)
	}
}
func (c *AdvuetController) Update() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	name := c.GetString("name")
	address := c.GetString("address")
	arr := models.Advert{
		Model:   gorm.Model{ID: uint(id)},
		Name:    name,
		Address: address,
	}
	models.DB.Debug().Model(&arr).Updates(&arr)
	c.Data["json"] = Rer{"200", "修改成功", id}
	c.ServeJSON(true)
}
func (c *AdvuetController) Show() {
	c.Ctx.Output.Header("Access-Control-Allow-Origin", "*")
	id, _ := c.GetInt("id")
	var show models.Advert
	models.DB.Debug().Where("id = ?", id).Find(&show)
	c.Data["json"] = Rer{"200", "详情成功", show}
	c.ServeJSON(true)
}
